import { defineStore } from 'pinia';
import type { RouteRecordRaw } from 'vue-router';
import { store } from '@/store';
import { login, logout } from '@/api/login';
import { AUTH_TOKEN_KEY, RUSTIC_ID_KEY } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
import { generatorDynamicRouter, getPermField } from '@/router/generator-router';
import { resetRouter } from '@/router';
import { getSysPermissionList } from '@/api/system/permission';
import { publicPathUrl } from '@/utils/common';
import { getUserInfo } from '@/api/system/user';
import { getRusticAdmin } from '@/api/rustic/rustic';

interface UserState {
  token: string;
  name: string;
  avatar: string;
  perms: string[];
  menus: RouteRecordRaw[];
  userInfo: Partial<API.AdminUserInfo>;
  rusticId: number;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: Storage.get(AUTH_TOKEN_KEY, null),
    name: '',
    avatar: '',
    perms: [],
    menus: [],
    userInfo: {},
    rusticId: Storage.get(RUSTIC_ID_KEY, 0),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getName(): string {
      return this.name;
    },
    getPerms(): string[] {
      return this.perms;
    },
  },
  actions: {
    // 初始化rusticId=0
    initRusticId() {
      Storage.clearRusticId();
      this.rusticId = 0;
    },
    // 更新 `rusticId` 的值，并保存到本地存储
    setRusticId(rusticId: number) {
      this.rusticId = rusticId;
      Storage.set(RUSTIC_ID_KEY, rusticId);
    },
    getRusticId() {
      if (this.rusticId == null || this.rusticId == 0) {
        const rusticId = Storage.get(RUSTIC_ID_KEY, null);
        if (rusticId != null && rusticId > 0) {
          this.setRusticId(rusticId);
        } else {
          return 0;
        }
      }
      return this.rusticId;
    },
    /** 清空token及用户信息 */
    resetToken() {
      this.avatar = this.token = this.name = '';
      this.perms = [];
      this.menus = [];
      this.userInfo = {};
      this.rusticId = 0;
      Storage.clear();
    },
    /** 登录成功保存token */
    setToken(token: string) {
      this.token = token ?? '';
      const ex = 7 * 24 * 60 * 60 * 1000;
      Storage.set(AUTH_TOKEN_KEY, this.token, ex);
    },
    /** 登录 */
    async login(params: API.LoginParams) {
      try {
        const res = await login(params);
        if (res) {
          const data = res.data;
          this.setToken(data?.token);
          return this.afterLogin();
        }
        return false;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    /** 登录成功之后, 获取用户信息以及生成权限路由 */
    async afterLogin() {
      try {
        const [{ data: userInfo }, { data: menus }] = await Promise.all([
          getUserInfo(),
          getSysPermissionList({ rusticId: this.rusticId }),
        ]);
        const perms = getPermField(userInfo?.permissionList || []);
        this.perms = perms;
        this.name = userInfo?.nickname;
        this.avatar = userInfo?.avatar ? publicPathUrl + userInfo?.avatar : '';
        this.userInfo = {
          ...userInfo,
          avatar: userInfo?.avatar ? publicPathUrl + userInfo?.avatar : '',
        };
        // 生成路由
        const generatorResult = await generatorDynamicRouter(menus || []);
        this.menus = generatorResult.menus.filter((item: any) => !item.meta?.hideInMenu);

        return { menus, perms, userInfo };
      } catch (error) {
        return Promise.reject(error);
        // return this.logout();
      }
    },
    /** 进入乡村 */
    async enterRustic(record: { rusticId: number }) {
      try {
        // const res = await getRusticAdmin({ rusticId: record.rusticId });
        const res = await getRusticAdmin({ rusticId: record.rusticId });
        if (res) {
          const data = res.data;
          const menus = data?.permissionList;
          const perms = getPermField(data?.permissionList || []);
          this.rusticId = data?.rusticId;
          this.setRusticId(this.rusticId);
          this.perms = perms;
          this.name = data?.nickname;
          this.avatar = data?.avatar ? publicPathUrl + data?.avatar : '';
          this.userInfo = {
            ...data,
            avatar: data?.avatar ? publicPathUrl + data?.avatar : '',
          };
          // 生成路由
          const generatorResult = await generatorDynamicRouter(data?.permissionList || []);
          this.menus = generatorResult.menus.filter((item: any) => !item.meta?.hideInMenu);

          return { menus, perms, data };
        }
        return false;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    /** 登出 */
    async logout() {
      await logout();
      this.resetToken();
      resetRouter();
    },
  },
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
